package org.jackysoft.portal.cfg;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.servlet.ServletContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.context.ServletContextAware;

@org.springframework.context.annotation.Configuration
public class PortalConfiguration implements ServletContextAware {

	static final Log logger = LogFactory.getLog(PortalConfiguration.class);

	private @Value("${rulesDir}")
	String fileDir;
	private @Value("${rulesIndexDir}")
	String indexDir;

	private ServletContext servletContext;

	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}

	public String getFileDir() {
		return fileDir;
	}

	public void setFileDir(String fileDir) {
		this.fileDir = fileDir;
	}

	public String getIndexDir() {
		return indexDir;
	}

	public void setIndexDir(String indexDir) {
		this.indexDir = indexDir;
	}

	public void removeDir(String dir) {
		try {
			logger.info("准备删除目录 " + dir);
			Process p = Runtime.getRuntime().exec("cmd /c del /s /q /f " + dir);
			String errorMsg = readInputStream(p.getErrorStream());
			String outputMsg = readInputStream(p.getInputStream());

			int c = p.waitFor();
			if (c != 0) {
				logger.error("处理失败：" + errorMsg);
			} else {// print command output
				logger.error(outputMsg);
			}

		} catch (IOException e) {
			logger.error(e);
		} catch (InterruptedException e) {
			logger.error(e);
		}

	}

	private String readInputStream(InputStream is) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(is));

		StringBuffer lines = new StringBuffer();
		for (String line = br.readLine(); line != null; line = br.readLine()) {
			lines.append(line);
		}
		br.close();
		return lines.toString();
	}

}
